#include "yb_form_xxcx.h"
#include "ui_yb_form_xxcx.h"
#include "pub_var.h"

#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QSettings>
#include <QMessageBox>
#include <QDebug>
#include <QSqlError>
#include <QSqlRecord>
#include <QDateTime>
#include <QFile>
#include <QFileDialog>

Form_xxcx::Form_xxcx(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_xxcx)
{
    ui->setupUi(this);

    //恢复当前窗口状态
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/xxcx").toRect();
    this->setGeometry(rct);
    ui->pb_export->setEnabled(false);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);
    mdPatient = new QSqlQueryModel; //患者列表
    mdDownResult = new QSqlQueryModel;    //下载结果

    //默认日期
    QDate dt;
    ui->deStart->setDate(dt.currentDate());
    ui->deEnd->setDate(dt.currentDate());

    request.setUrl(QUrl(pub::hos_ybjy));

    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    tm = new QTimer(this);
    connect(tm, SIGNAL(timeout()), this, SLOT(onTimeOut()));
    ui->leStatus->setEnabled(false);


    qrm->exec("select code from com_dict_com where dic_type = '险种' order by code");
    ui->cbbXz->clear();
    while(qrm->next())
    {
        ui->cbbXz->addItem(qrm->value(0).toString());
    }

    isInsu = true;
    ui->gbOwn->setVisible(false);
    ui->cbbJsid->setEnabled(false);

    dlgDelay = new Pub_pop_delay(); //弹出窗口

    //建立明细查询临时表
    sq = "create temporary table if not exists tmp_down_5204"
         " (mdtrt_id varchar(30),setl_id varchar(30),feedetl_sn varchar(30),rx_drord_no varchar(30),med_type varchar(6),"
         "fee_ocur_time datetime , cnt decimal(16,4),pric decimal(16,6),sin_dos_dscr varchar(200),used_frqu_dscr varchar(200),"
         "prd_days decimal(4,2),medc_way_dscr varchar(200), det_item_fee_sumamt decimal(16,2),pric_uplmt_amt decimal(16,6),"
         "selfpay_prop decimal(5,4),fulamt_ownpay_amt decimal(16,2),overlmt_amt decimal(16,2), preselfpay_amt decimal(16,2),"
         "inscp_scp_amt decimal(16,2),chrgitm_lv varchar(3),hilist_code varchar(50),hilist_name varchar(200),list_type varchar(6),"
         "med_list_codg varchar(50),medins_list_codg varchar(150),medins_list_name varchar(100),med_chrgitm_type varchar(6),"
         "prodname varchar(200), spec varchar(200),dosform_name varchar(200),bilg_dept_codg varchar(30),"
         "bilg_dept_name varchar(100),bilg_dr_codg varchar(30),bilg_dr_name varchar(50), acord_dept_codg varchar(30),"
         "acord_dept_name varchar(100),orders_dr_code varchar(30),orders_dr_name varchar(50),lmt_used_flag varchar(3),"
         "hosp_prep_flag varchar(3),hosp_appr_flag varchar(3),tcmdrug_used_way varchar(6),prodplac_type varchar(6),"
         "bas_medn_flag varchar(3),hi_nego_drug_flag varchar(3),chld_medc_flag varchar(3),etip_flag varchar(3),"
         "etip_hosp_code varchar(30),dscg_tkdrug_flag varchar(3),list_sp_item_flag varchar(3),matn_fee_flag varchar(6),"
         "drt_reim_flag varchar(3),memo varchar(500),opter_id varchar(20),opter_name varchar(50),opt_time datetime ,"
         "atinc integer auto_increment primary key)";
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"错误","建立明细查询临时表失败！");
        ui->pb5204->setEnabled(false);
    }

    //累计查询临时表
    sq = "create temporary table if not exists tmp_down_5206"
         " (insutype varchar(6)," //险种类型	字符型	6
         " year varchar(4),"//年度	字符型	4
         " cum_ym varchar(6),"//累计年月	字符型	6
         " cum_type_code varchar(30),"//	累计类别代码	字符型	10
         " cum decimal(16,2))";//累计值	数值型	16,2
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"错误","建立累计查询临时表失败！");
        ui->pb5206->setEnabled(false);
    }


    //检查用户权限
    has_insu_privilege = false; //预置为无权限

    sq = "select name from com_privileges where role_dept = '医保管理员'"
         " and name = '" + pub::usr_name + "'";
    qrm->exec(sq);


    if(qrm->next())
    {
        //有权限
        has_insu_privilege = true;

    }

}

Form_xxcx::~Form_xxcx()
{
    delete ui;
}

void Form_xxcx::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/xxcx", QVariant(this->geometry()));
    emit destroyW( "xxcx" );
}


void Form_xxcx::on_pb5201_clicked()
{

    ui->pb_export->setEnabled(false);
    current_query = "";

    //就诊信息查询
    curMsg = "执行 5201 交易 。。。";
    tm->start(300);
    QJsonObject in;
    putBaseIn(  in, "5201") ;

    QJsonObject inpu,inpud;

    inpu.insert("psn_no", psn_no);//
    inpu.insert("begntime", ui->deStart->date().toString("yyyy-MM-dd")+" 00:00:00");//开始日期
    inpu.insert("endtime", ui->deEnd->date().toString("yyyy-MM-dd")+" 23:59:59");//结束日期
    inpu.insert("med_type", ui->cbbYllb->currentText());//医疗类别
    //inpu.insert("mdtrt_id", "2100659508");//


    inpud.insert("data",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);
    qDebug()<<"5201 indoc "<<indoc;

    //保存入参日志
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    QNetworkReply* reply = manager.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。

    qDebug()<<" request 5201 is returned";

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        tm->stop();
        return ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        tm->stop();
        return ;
    }

    QByteArray bt = reply->readAll();
    QString t = QString::fromLocal8Bit(bt);

    QJsonParseError json_error;
    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());
        tm->stop();
        return ;
    }
    qDebug()<< "5201 outDoc "<<jsdc;
    QJsonObject jsob = jsdc.object();

    sq = "update com_business set  tmstmp = now(), v_out = '"
            + jsdc.toJson(QJsonDocument::Compact)
            + "' , infcode = "
            + QString::number(jsob.value("infcode").toInt())
             +  " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }

    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意","5201 交易失败：" + t );
        tm->stop();
        return ;
    }
    ret5201 = jsob.value("output").toObject().value("mdtrtinfo").toArray();
    ui->lwResult->clear();
    ui->lwResult->addItem( "mdtrt_id \t insutype \t psn_type \t med_type \t begntime \t endtime");
    for(int i = 0; i< ret5201.size();  i++){
        ui->lwResult->addItem( ret5201[i].toObject().value("mdtrt_id").toString()
                               + "\t"
                               + ret5201[i].toObject().value("insutype").toString()
                               + "\t"
                               + ret5201[i].toObject().value("psn_type").toString()
                               + "\t"
                               + ret5201[i].toObject().value("med_type").toString()
                               + "\t"
                               + ret5201[i].toObject().value("begntime").toString()
                               + "\t"
                               + ret5201[i].toObject().value("endtime").toString()

                               );
    }
    tm->stop();
    QMessageBox::information(this,"注意","查询结束！");

}

void Form_xxcx::on_pb5202_clicked()
{

   ui->pb_export->setEnabled(false);
    current_query = "";

    //诊断信息查询
    QJsonObject in;
    putBaseIn(  in, "5202") ;

    QJsonObject inpu,inpud;

    inpu.insert("psn_no", psn_no);//
    inpu.insert("mdtrt_id", ui->leJzid->text());//


    inpud.insert("data",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);
    qDebug()<<"5202 indoc "<<indoc;

    //保存入参日志
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    QNetworkReply* reply = manager.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。

    qDebug()<<" request 5202 is returned";

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        return ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return ;
    }

    QByteArray bt = reply->readAll();
    QString t = QString::fromLocal8Bit(bt);

    QJsonParseError json_error;
    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());

        return ;
    }
    qDebug()<< "5202 outDoc "<<jsdc;
    QJsonObject jsob = jsdc.object();

    sq = "update com_business set  tmstmp = now(), v_out = '"
            + jsdc.toJson(QJsonDocument::Compact)
            + "' , infcode = "
            + QString::number(jsob.value("infcode").toInt())
             +  " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }

    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意","5202 交易失败：" + t );

        return ;
    }
    ret5202 = jsob.value("output").toObject().value("diseinfo").toArray();
    ui->lwResult->clear();
    ui->lwResult->addItem("diag_info_id \t diag_code \t diag_name \t dise_dor_nam");
    for(int i = 0; i< ret5202.size();  i++){
        ui->lwResult->addItem( ret5202[i].toObject().value("diag_info_id").toString()
                               +"\t"
                               +ret5202[i].toObject().value("diag_code").toString()
                               +"\t"
                               +ret5202[i].toObject().value("diag_name").toString()
                               +"\t"
                               +ret5202[i].toObject().value("dise_dor_nam").toString()
                               );

    }

    QMessageBox::information(this,"注意","查询结束！");
}

void Form_xxcx::on_pb5203_clicked()
{

    ui->pb_export->setEnabled(false);

    current_query = "";

    //结算信息查询
    dlgDelay->setText("正在提取数据。。。");
    dlgDelay->setModal(true);
    dlgDelay->setNeedClose(false);
    dlgDelay->show();
    qApp->processEvents();

    QJsonObject in;
    putBaseIn(  in, "5203") ;

    QJsonObject inpu,inpud;

    inpu.insert("psn_no", psn_no);//
    inpu.insert("setl_id", ui->cbbJsid->currentText());//
    inpu.insert("mdtrt_id", ui->leJzid->text());//


    inpud.insert("data",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);
    qDebug()<<"5203 indoc "<<indoc;

    //保存入参日志
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    QNetworkReply* reply = manager.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。

    qDebug()<<" request 5203 is returned";

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();
        return ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();
        return ;
    }

    QByteArray bt = reply->readAll();
    QString t = QString::fromLocal8Bit(bt);

    QJsonParseError json_error;
    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());
        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();
        return ;
    }
    qDebug()<< "5203 outDoc "<<jsdc;
    QJsonObject jsob = jsdc.object();

    sq = "update com_business set  tmstmp = now(), v_out = '"
            + jsdc.toJson(QJsonDocument::Compact)
            + "' , infcode = "
            + QString::number(jsob.value("infcode").toInt())
             +  "  where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }

    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意","5203 交易失败：" + t );
        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();
        return ;
    }

    ret5203info = jsob.value("output").toObject().value("setlinfo").toObject();
    ret5203detail = jsob.value("output").toObject().value("setldetail").toArray();

    qDebug()<<ret5203info;
               qDebug()<<jsob.value("output").toObject();

    ui->lwResult->clear();

    QString result = "总额:" + QString::asprintf("%.2f",ret5203info.value("medfee_sumamt").toDouble());
    result += "，基金支出:" + QString::asprintf("%.2f",ret5203info.value("fund_pay_sumamt").toDouble());
    result += "，个人账户支出:" + QString::asprintf("%.2f",ret5203info.value("acct_pay").toDouble());
    result += "(其中家庭共济支付："+ QString::asprintf("%.2f",ret5203info.value("acct_mulaid_pay").toDouble())+")";
    result += "，现金支出:" + QString::asprintf("%.2f",ret5203info.value("cash_payamt").toDouble());
    result += "，账户余额:" + QString::asprintf("%.2f",ret5203info.value("balc").toDouble());
    //result += "\n"
    ui->lwResult->addItem( result );
    result = "先行自付金额:" + QString::asprintf("%.2f",ret5203info.value("preselfpay_amt").toDouble());
    result += "，符合政策金额："+ QString::asprintf("%.2f",ret5203info.value("inscp_scp_amt").toDouble());
    result += "，本次支付起付线:" + QString::asprintf("%.2f",ret5203info.value("act_pay_dedc").toDouble());
    result += "，报销比例:" + QString::asprintf("%.2f",ret5203info.value("pool_prop_selfpay").toDouble());
    ui->lwResult->addItem( result );
    result = "（报销明细） 基本医疗保险:" + QString::asprintf("%.2f",ret5203info.value("hifp_pay").toDouble());
    result += "，公补:" + QString::asprintf("%.2f",ret5203info.value("cvlserv_pay").toDouble());
    result += "，企补："+ QString::asprintf("%.2f",ret5203info.value("hifes_pay").toDouble());
    result += "，居民大病:" + QString::asprintf("%.2f",ret5203info.value("hifmi_pay").toDouble());
    result += "，职工大额:" + QString::asprintf("%.2f",ret5203info.value("hifob_pay").toDouble());
    result += "，医疗救助:" + QString::asprintf("%.2f",ret5203info.value("maf_pay").toDouble());
    result += "，优抚对象："+ QString::asprintf("%.2f",ret5203info.value("PREF_FUND_PAY").toDouble());
    result += "，其他:" + QString::asprintf("%.2f",ret5203info.value("oth_pay").toDouble());
    ui->lwResult->addItem( result );


    dlgDelay->setNeedClose(true);
    dlgDelay->closeWindow();
}

void Form_xxcx::on_pbExit_clicked()
{
    this->close();
}

void Form_xxcx::putBaseIn( QJsonObject &in, QString code)
{
    QString inp;
    inp = pub::getYbStrJ(code,"");   //
    if(inp.isEmpty()){
        //pub::useInsurance = false;  //设置医保不可用
        QMessageBox::information(this,"note","申请交易流水号失败！");
        return; //未能成功申请交易流水号
    }

    currentMsgid = inp;

    in.insert("infno", code);
    in.insert( "msgid", inp);
    in.insert("mdtrtarea_admvs", pub::hos_insuplc);
    //in.insert("insuplc_admdvs", mpPerson["insuplc_admdvs"] );

    in.insert("insuplc_admdvs","210100");
    in.insert("recer_sys_code", "OwnSoft");
    in.insert("dev_no","");
    in.insert("dev_safe_info","");
    in.insert("cainfo", pub::hos_secretcode);
    in.insert("signtype","");
    in.insert("infver", "V1.0");
    in.insert("opter_type", "1");
    in.insert("opter", pub::usr_code);
    in.insert("opter_name", pub::usr_name);
    in.insert("inf_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    in.insert("fixmedins_code", pub::hos_ybbh);
    in.insert("fixmedins_name", pub::hos_name);
    in.insert("sign_no", pub::sign_no);

}

void Form_xxcx::onTimeOut()
{
    if(ui->leStatus->text().isEmpty()){
        ui->leStatus->setText(curMsg);
    }else{
        ui->leStatus->clear();
    }
    qApp->processEvents();
}

void Form_xxcx::on_pbDycx_clicked()
{

    ui->pb_export->setEnabled(false);
    current_query = "";

    //待遇查询
    QJsonObject in;
    putBaseIn(  in, "2001") ;

    QJsonObject inpu,inpud;

    inpu.insert("psn_no", psn_no);//
    inpu.insert("insutype", ui->cbbXz->currentText());   //险种类型
    inpu.insert("fixmedins_code", pub::hos_ybbh); //定点医药机构编号
    inpu.insert("med_type", "11"); //医疗类别
    inpu.insert("begntime", ui->deStart->date().toString("yyyy-MM-dd")+" 00:00:00");       //开始时间

    inpud.insert("data",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);
    qDebug()<<"2001 indoc "<<indoc;

    //保存入参日志
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    QNetworkReply* reply = manager.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。

    qDebug()<<" request 2001 is returned";

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        return ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return ;
    }

    QByteArray bt = reply->readAll();
    QString t = QString::fromLocal8Bit(bt);

    QJsonParseError json_error;
    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());

        return ;
    }
    qDebug()<< "2001 outDoc "<<jsdc;
    QJsonObject jsob = jsdc.object();

    sq = "update com_business set  tmstmp = now(), v_out = '"
            + jsdc.toJson(QJsonDocument::Compact)
            + "' , infcode = "
            + QString::number(jsob.value("infcode").toInt())
             +  " where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }

    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意","2001 交易失败：" + t );

        return ;
    }

    QJsonArray jsar = jsob.value("output").toObject().value("trtinfo").toArray();

    ui->lwResult->clear();
    ui->lwResult->addItem("trt_chk_type\tfund_pay_type\ttrt_enjymnt_flag\tbegndate\tenddate\ttrt_chk_rslt");

    QJsonArray::iterator it = jsar.begin();

    while(it != jsar.end()){

        QString trt_chk_type = it->toObject().value("trt_chk_type").toString();
        QString fund_pay_type = it->toObject().value("fund_pay_type").toString();
        QString trt_enjymnt_flag = it->toObject().value("trt_enjymnt_flag").toString();
        QString trt_chk_rslt ;

        sq = "select dic_label from com_dict_new where dic_type = 'trt_chk_type' and dic_value = '" + trt_chk_type + "'";
        qrm->exec(sq);
        if(qrm->next())
        {
            trt_chk_type = qrm->value(0).toString();
        }

        sq = "select dic_label from com_dict_new where dic_type = 'fund_pay_type' and dic_value = '" + fund_pay_type + "'";
        qrm->exec(sq);
        if(qrm->next())
        {
            fund_pay_type = qrm->value(0).toString();
        }

        sq = "select dic_label from com_dict_new where dic_type = 'trt_enjymnt_flag' and dic_value = '" + trt_enjymnt_flag + "'";
        qrm->exec(sq);
        if(qrm->next())
        {
            trt_enjymnt_flag = qrm->value(0).toString();
        }


        QString tmp = trt_chk_type;
        tmp.append("\t");
        tmp.append(fund_pay_type);
        tmp.append("\t");
        tmp.append(trt_enjymnt_flag);
        tmp.append("\t");
        tmp.append(it->toObject().value("begndate").toString());
        tmp.append("\t");
        tmp.append(it->toObject().value("enddate").toString());
        tmp.append("\t");
        tmp.append(it->toObject().value("trt_chk_rslt").toString());

        ui->lwResult->addItem(tmp);
        it ++ ;
    }
    ui->verticalLayout_2->setStretch(3,3);
    ui->verticalLayout_2->setStretch(4,1);
    QMessageBox::information(this,"注意","查询结束！");
}

void Form_xxcx::on_pbInsu_clicked()
{

    if(!ui->ckb_date_constrain->isChecked() && !ui->ckb_id_constrain->isChecked())
    {
        QMessageBox::information(this,"注意","日期范围和ID限定至少要选择一项！");
        return;
    }

    sq = "select name 姓名,card_no 病志, dept_name 诊室,"
         " inpatient_no,idenno , psn_no, mdtrt_id , in_date 就诊日期"
         " from fin_ipr_siinmaininfo where ";
    sq += " balance_no = '0' and insutype = '" + ui->cbbXz->currentText() + "' ";

    if(ui->ckb_date_constrain->isChecked())
    {
        sq += " and in_date > to_date('"
                + ui->deStart->date().toString("yyyy-MM-dd")
                +"','yyyy/mm/dd') ";
        sq += " and in_date< to_date('"
                + ui->deEnd->date().toString("yyyy-MM-dd")
                + " 23:59:59','yyyy/mm/dd hh24:mi:ss') ";
    }

    QString id = ui->le_id->text().trimmed();
    QString constrain_type = ui->cbb_id_type->currentText();
qDebug()<<"id,constrain_type : "<<id<<" , "<<constrain_type<<"\n";
    if(id.isEmpty() && ui->ckb_id_constrain->isChecked())
    {
        QMessageBox::information(this, "注意", "选择ID限定，但限定内容为空。");
        return;
    }

    if(!id.isEmpty() && ui->ckb_id_constrain->isChecked())
    {
        if( constrain_type == "病志号(card_no)")
        {
            sq += " and card_no = '" + pub::add0(id, 10) + "'";
        }
        else if(constrain_type == "就诊ID(mdtrt_id)")
        {
            sq += " and mdtrt_id = '" + id + "'";
        }
        else if(constrain_type == "医保编号(psn_no)")
        {
            sq += " and psn_no = '" + id + "'";
        }
        else if(constrain_type == "clinic_code")
        {
            sq += " and inpatient_no = '" + id + "'";
        }
        else if(constrain_type == "身份证号(idenno)")
        {
            sq += " and idenno = '" + id + "'";
        }


    }

    sq += " order by in_date" ;

    qDebug()<<"提取患者名单："<<sq;
    mdPatient->setQuery(sq, pub::db_o);

    if(mdPatient->rowCount() < 1)
    {
        QMessageBox::information(this, "注意", "按限定条件检索内容为空！");
        return;
    }

    ui->tvPatient->setModel(mdPatient);
    int width = ui->tvPatient->width();
    pub::setColumnWidth(ui->tvPatient, "0.2^0.22^0.22^0^0^0^0^0.25", width, 10);

    isInsu = true;  //设置当前状态为医保
    ui->gbOwn->setVisible(false);
    ui->gbInsu->setVisible(true);

}

void Form_xxcx::on_pbOwnPay_clicked()
{

    if(!ui->ckb_date_constrain->isChecked() && !ui->ckb_id_constrain->isChecked())
    {
        QMessageBox::information(this,"注意","日期范围和ID限定至少要选择一项！");
        return;
    }

    sq = "select name 姓名, card_no 病志, dept_name 诊室, "
         " clinic_code, idenno , reg_date 就诊日期"
         " from fin_opr_register where valid_flag = '1' and ";
    if(ui->ckb_date_constrain->isChecked())
    {
    sq += " oper_date > to_date('"
            + ui->deStart->date().toString("yyyy-MM-dd")
            + "','yyyy/mm/dd') ";
    sq += " and oper_date< to_date('"
            + ui->deEnd->date().toString("yyyy-MM-dd")
            + " 23:59:59','yyyy/mm/dd hh24:mi:ss')";
    }
    sq += " and pact_code = '1'  order by reg_date" ; //and upld_flg0 = '1'


    QString id = ui->le_id->text().trimmed();

    if(id.isEmpty() && ui->ckb_id_constrain->isChecked())
    {
        QMessageBox::information(this, "注意", "选择ID限定，但限定内容为空。");
        return;
    }

    if(!id.isEmpty()  && ui->ckb_id_constrain->isChecked())
    {
        if(ui->cbb_id_type->currentText() == "病志号(card_no)")
        {
            sq += " and card_no = '" + pub::add0(id, 10) + "'";
        }
        else if(ui->cbb_id_type->currentText() == "身份证号(idenno)")
        {
            sq += " and idenno = '" + id + "'";
        }
        else if(ui->cbb_id_type->currentText() == "clinic_code")
        {
            sq += " and clinic_code = '" + id + "'";
        }
        else
        {
            QMessageBox::information(this, "注意", "自费查询限定只能是病志号，身份证号或clinic_code");
            return;
        }

    }


    qro->exec(sq);

    mdPatient->setQuery(sq, pub::db_o);

    if(mdPatient->rowCount() < 1)
    {
        QMessageBox::information(this, "注意", "按限定条件检索内容为空！");
        return;
    }

    int width = ui->tvPatient->width();

    ui->tvPatient->setModel(mdPatient);
    ui->tvPatient->setColumnWidth(0, width * 0.20);
    ui->tvPatient->setColumnWidth(1, width * 0.22);
    ui->tvPatient->setColumnWidth(2, width * 0.22);
    ui->tvPatient->setColumnHidden(3 ,true);
    ui->tvPatient->setColumnHidden(4 ,true);
    ui->tvPatient->setColumnWidth(5, width * 0.25);

    isInsu = false;  //设置当前状态为自费
    ui->gbOwn->setVisible(true);
    ui->gbInsu->setVisible(false);

}

void Form_xxcx::on_tvPatient_doubleClicked(const QModelIndex &index)
{
    on_tvPatient_clicked(index);
}

void Form_xxcx::on_tvPatient_clicked(const QModelIndex &index)
{

    clinic_code = index.siblingAtColumn(3).data(0).toString();
    name = index.siblingAtColumn(0).data(0).toString();
    idenno = index.siblingAtColumn(4).data(0).toString();
    ui->leMzh->setText(index.siblingAtColumn(1).data(0).toString());
    ui->leXm->setText( name );
    ui->leClinicCode->setText(clinic_code);

    ui->tvResult->setModel(NULL);
    ui->lwResult->clear();

    if(isInsu)  //医保
    {
        psn_no = index.siblingAtColumn(5).data(0).toString();
        mdtrt_id = index.siblingAtColumn(6).data(0).toString();
        ui->leJzid->setText(mdtrt_id);

        sq = "select setl_id, invoice_no from fin_ipr_siinmaininfo where inpatient_no = '" + clinic_code + "'";
        qro->exec(sq);

        ui->cbbJsid->clear();
        ui->cbbInvoice->clear();

        while(qro->next()){

            ui->cbbJsid->addItem( qro->value(0).toString());
            ui->cbbInvoice->addItem( qro->value(1).toString());
        }
    }
    else    //自费
    {

    }
}

void Form_xxcx::on_pbFymxZf_clicked()
{

    current_query = "";

    //自费费用明细
    if(ui->leXm->text().isEmpty())
    {
        QMessageBox::information(this, "注意","请指定患者之后再进行查询！");
        return;
    }

    QJsonObject in ;
    in.insert("fixmedins_mdtrt_id", clinic_code);//医药机构就诊ID	字符型	30
    in.insert("fixmedins_code", pub::hos_ybbh);//	定点医药机构编号	字符型	30
    in.insert("page_num", 1);//	当前页数	数值型	4
    in.insert("page_size", 10);//	本页数据量	数值型	4

    QJsonObject jsonRet;    //医保交易返回的Json数据
    QString info;   //如果返回错误，保存错误信息
    curMsg = "正在执行交易4207，查询自费患者费用明细...";
    ui->leStatus->setText(curMsg);
    qApp->processEvents();
    tm->start(300);
    if( ! pub::call_business( "4207", in, info, jsonRet, "", true , manager, request))
    {
        QMessageBox::warning(this, "注意", info);

    }else
    {
        QJsonArray retData = jsonRet.value("output").toObject().value("data").toArray();

        int recCount = retData.size();

        if(recCount == 0){
            QMessageBox::information(this, "注意", " 查询结束，无返回数据！");
            ui->leStatus->setText("");

        }else{
            QString outText;
            outText += "医师姓名\t商品名\t数量\t单价\t费用合计\n";
            for(int i = 0; i< recCount; i ++)
            {
                outText += retData[i].toObject().value("bilgDrName").toString() + "\t";
                outText += retData[i].toObject().value("prodname").toString() + "\t";
                outText += QString::number(retData[i].toObject().value("cnt").toDouble()) + "\t";
                outText += QString::number(retData[i].toObject().value("pric").toDouble()) + "\t";
                outText += QString::number(retData[i].toObject().value("detItemFeeSumamt").toDouble()) + "\n";
            }
            ui->lwResult->clear();
            ui->lwResult->addItem(outText);
        }
    }
    tm->stop();
    ui->leStatus->clear();
}

void Form_xxcx::on_pbJzxxZf_clicked()
{

    current_query = "";

    //自费就诊查询
    QJsonObject in ;
    in.insert("begntime", ui->deStart->date().toString("yyyy-MM-dd 00:00:00"));//开始时间	日期型				yyyy-MM-dd HH:mm:ss
    in.insert("endtime", ui->deEnd->date().toString("yyyy-MM-dd 23:59:59"));//结束时间	日期型				yyyy-MM-dd HH:mm:ss
    in.insert("page_num", 1);//	当前页数	数值型	4
    in.insert("page_size", 10);//	本页数据量	数值型	4

    QJsonObject jsonRet;    //医保交易返回的Json数据
    QString info;   //如果返回错误，保存错误信息
    curMsg = "正在执行交易4208，查询自费患者就诊信息...";
    ui->leStatus->setText(curMsg);
    qApp->processEvents();

    tm->start(300);
    if( ! pub::call_business( "4208", in, info, jsonRet, "", true , manager, request))
    {
        QMessageBox::warning(this, "注意", info);

    }else
    {

        QJsonArray retData = jsonRet.value("output").toObject().value("data").toArray();

        int recCount = retData.size();

        if(recCount == 0){
            QMessageBox::information(this, "注意", " 查询结束，无返回数据！");
            ui->leStatus->setText("");

        }else{

            QString outText;
            outText += "就诊ID\t证件类型\t证件号码\t人员姓名\n";
            for(int i = 0; i< recCount; i ++)
            {
                outText += retData[i].toObject().value("fixmedinsMdtrtId").toString() + "\t";
                outText += retData[i].toObject().value("psnCertType").toString() + "\t";
                outText += retData[i].toObject().value("certno").toString() + "\t";
                outText += retData[i].toObject().value("psnName").toString() + "\n";
            }
            ui->lwResult->clear();
            ui->lwResult->addItem(outText);
        }
    }
    tm->stop();
    ui->leStatus->clear();
}

void Form_xxcx::on_pbZdxxZf_clicked()
{

    current_query = "";

    //自费诊断查询
    if(ui->leXm->text().isEmpty())
    {
        QMessageBox::information(this, "注意","请指定患者之后再进行查询！");
        return;
    }

    QJsonObject in ;
    in.insert("fixmedins_mdtrt_id", clinic_code);//医药机构就诊ID	字符型	30
    in.insert("fixmedins_code", pub::hos_ybbh);//	定点医药机构编号	字符型	30
    in.insert("page_num", 1);//	当前页数	数值型	4
    in.insert("page_size", 10);//	本页数据量	数值型	4

    QJsonObject jsonRet;    //医保交易返回的Json数据
    QString info;   //如果返回错误，保存错误信息
    curMsg = "正在执行交易4209，查询自费患者诊断...";
    ui->leStatus->setText(curMsg);
    qApp->processEvents();

    tm->start(300);
    if( ! pub::call_business( "4209", in, info, jsonRet, "", true , manager, request))
    {
        QMessageBox::warning(this, "注意", info);

    }else
    {

        QJsonArray retData = jsonRet.value("output").toObject().value("data").toArray();

        int recCount = retData.size();

        if(recCount == 0){
            QMessageBox::information(this, "注意", " 查询结束，无返回数据！");
            ui->leStatus->setText("");

        }else{
            QString outText;
            for(int i = 0; i< recCount; i ++)
            {
                outText += "诊断时间 : " + retData[i].toObject().value("diagTime").toString() + "\n";
                outText += "诊断科室 : " + retData[i].toObject().value("diagDept").toString() + "\n";
                outText += "医师姓名 : " + retData[i].toObject().value("diagDrName").toString() + "\n";
                outText += "诊断名称 : " + retData[i].toObject().value("diagName").toString() + "\n";
                outText += "诊断代码 : " + retData[i].toObject().value("diagCode").toString() + "\n";
            }
            ui->lwResult->clear();
            ui->lwResult->addItem(outText);
        }
    }
    tm->stop();
    ui->leStatus->clear();
}

void Form_xxcx::on_pb5204_clicked()
{

   ui->pb_export->setEnabled(false);
    current_query = "";
    //结算明细信息查询
    dlgDelay->setText("正在提取数据。。。");
    dlgDelay->setModal(true);
    dlgDelay->setNeedClose(false);
    dlgDelay->show();
    qApp->processEvents();

    qrm->exec("delete from tmp_down_5204");

    QJsonObject in;   //医保交易入参信息
    QJsonObject inpu; //data 节点
    inpu.insert("psn_no", psn_no);//
    inpu.insert("setl_id", ui->cbbJsid->currentText());//
    inpu.insert("mdtrt_id", ui->leJzid->text());//
    in.insert("data", inpu); //

    QString info;   //返回信息
    QJsonObject jsonRet; //返回 json 数据

    if( ! pub::call_business("5204", in, info, jsonRet, "", true , manager, request))
    {
        QMessageBox::warning(this, "注意", info);
        qDebug()<<"5204 business return error.";
        qDebug()<<info;
        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();
        return ;
    }


    //查询指定交易出参数据结构
    sq = "select node_name,para_code,para_name,type,len,code_flag,is_key,local_tab,local_col "
         " from com_down_para where in_out = 'out' and busi_code = '5204' ";
    qrm->exec(sq);

    QStringList para_code_out,para_type_out;

    while(qrm->next()){
        para_code_out << qrm->value(1).toString();
        para_type_out << qrm->value(3).toString();
    }

    int fieldsCount = para_code_out.size();

    if(fieldsCount == 0)    {
        ui->lwResult->addItem( "字段列表无效！");
        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();
        return;
    }


        QJsonArray retData = jsonRet.value("output").toArray();

        int recCount = retData.size();

        if(recCount == 0){
            QMessageBox::information(this, "注意", "5204 查询无结果。");    //返回正常但无数据
            ui->leStatus->setText("");
            dlgDelay->setNeedClose(true);
            dlgDelay->closeWindow();
            return;
        }

        int recNow = recCount;

        while(recNow > 0){

            recNow--;

            QString fields, values; //字段列表，返回值列表
            int i = 0;
            bool isFirstField = true; //是否是第一个字段。第一个字段的字串不需要前导分隔符
            while(true)
            {
                QString retV;
                if(para_type_out[i] == "decimal")
                {
                    retV = QString::number(retData[recNow].toObject().value(para_code_out[i]).toDouble());
                }
                else
                {
                    //过滤字段中对 mysql 有干扰的特殊字符，反斜杠，单引号等。
                    retV = retData[recNow].toObject().value(para_code_out[i]).toString();
                    retV.replace("\\","/");
                    retV.replace("'","\\'");
                }

                if(!retV.isEmpty() )  //只保存非空字段
                {
                    if(isFirstField)
                    {
                        isFirstField = false;
                        fields += para_code_out[i];
                        values += "'" + retV + "'";
                    }else{
                        fields += ", " + para_code_out[i];
                        values += ", '" + retV + "'";
                    }
                }

                i++;
                if(i >= fieldsCount)    //本行数据是否处理完成
                {
                    break;
                }
            }

            //replace 插入数据，重复数据直接替换。对 atinc 字段有影响。
            sq = "insert into tmp_down_5204 (" + fields + ") values (" + values + ")";

            if(!qrm->exec(sq)){
                ui->lwResult->addItem( " 插入记录错误！\nerrMsg:  "+ qrm->lastError().text() + "\n" + sq  + "\n");
                dlgDelay->setNeedClose(true);
                dlgDelay->closeWindow();
                    return;

            }
        }

    sq = "select hilist_name 项目名称,"
         "case when chrgitm_lv = '01' then '甲' else "
         "( case when chrgitm_lv = '02' then '乙' else "
         "( case when chrgitm_lv = '03' then '丙' else '' end)end) end 等级,"
         " cnt 数量, pric 单价, det_item_fee_sumamt 金额, concat(concat(selfpay_prop ,' / '), preselfpay_amt) 先行自付比例金额, ";
    sq += "case when pric_uplmt_amt = '999999' then '无' else pric_uplmt_amt end 限价, "
          //" case when pric > pric_uplmt_amt then det_item_fee_sumamt - ( pric_uplmt_amt * cnt)"
          //" else 0 end 超限金额, "
          " inscp_scp_amt 符合政策, fulamt_ownpay_amt 自费金额 ";//overlmt_amt 超限金额
    sq += " from tmp_down_5204 order by atinc";

    last_query = "m" + sq;
    ui->pb_export->setEnabled(true);

    mdDownResult->setQuery(sq, pub::db_m);
    ui->tvResult->setModel(mdDownResult);
    pub::setColumnWidth(ui->tvResult, "0.15^0.05^0.05^0.15^0.1^0.15^0.1^0.1^0.1", ui->tvResult->width());
    dlgDelay->setNeedClose(true);
    dlgDelay->closeWindow();
    ui->verticalLayout_2->setStretch(3,1);
    ui->verticalLayout_2->setStretch(4,3);
}

void Form_xxcx::on_cbbInvoice_currentTextChanged(const QString &arg1)
{
    sq = "select setl_id, invoice_no from fin_ipr_siinmaininfo where inpatient_no = '"
            + clinic_code + "' and invoice_no = '" + arg1 + "'";
    qDebug()<<sq;
    qrot->exec(sq);
    qrot->next();
    ui->cbbJsid->setCurrentText( qrot->value(0).toString());
}

void Form_xxcx::on_cbbJsid_currentTextChanged(const QString &arg1)
{

}

void Form_xxcx::on_pb1101_clicked()
{

    ui->pb_export->setEnabled(false);
    current_query = "";

    sq = "select v_out from com_business where clinic_code = '" + clinic_code + "' and ywbh = '1101' order by atinc desc";
    qrm->exec(sq);
    if(qrm->next())
    {
        QString js = qrm->value(0).toString();
        QJsonDocument jsdc = QJsonDocument::fromJson(js.toUtf8());
        QJsonObject jsob = jsdc.object();

        QJsonObject baseinfo = jsob.value("output").toObject().value("baseinfo").toObject();
        QJsonArray insuinfo = jsob.value("output").toObject().value("insuinfo").toArray();

        ui->lwResult->clear();
        QString tmp = "姓名：" + baseinfo["psn_name"].toString();
        tmp += "   人员编号：" + baseinfo["psn_no"].toString();
        tmp += "   身份证号：" + baseinfo["certno"].toString();
        ui->lwResult->addItem(tmp);

        QString psn_type, psn_insu_stas, insutype, psn_insu_date, paus_insu_date,balc;
        for(int i = 0; i<insuinfo.size(); i++)
        {
            psn_type = insuinfo[i].toObject()["psn_type"].toString();
            psn_insu_stas = insuinfo[i].toObject()["psn_insu_stas"].toString();
            insutype = insuinfo[i].toObject()["insutype"].toString();
            psn_insu_date = insuinfo[i].toObject()["psn_insu_date"].toString();
            paus_insu_date = insuinfo[i].toObject()["paus_insu_date"].toString();
            balc = QString::number(insuinfo[i].toObject()["balc"].toDouble(),'f',2);

            sq = "select dic_label from com_dict_new where dic_type = 'psn_type' and dic_value = '" + psn_type + "'";
            qrm->exec(sq);
            if(qrm->next())
            {
                psn_type = qrm->value(0).toString();
            }

            sq = "select dic_label from com_dict_new where dic_type = 'psn_insu_stas' and dic_value = '" + psn_insu_stas + "'";
            qrm->exec(sq);
            if(qrm->next())
            {
                psn_insu_stas = qrm->value(0).toString();
            }

            sq = "select dic_label from com_dict_new where dic_type = 'insutype' and dic_value = '" + insutype + "'";
            qrm->exec(sq);
            if(qrm->next())
            {
                insutype = qrm->value(0).toString();
            }

            tmp = "险种：" + insutype;
            tmp += "   身份：" + psn_type;
            tmp += "   状态：" + psn_insu_stas;
            tmp += "   起始日期；" + psn_insu_date;
            if(!paus_insu_date.isEmpty())
            {
                tmp += "   停保日期：" + paus_insu_date;
            }
            if(!balc.isEmpty())
            {
                tmp += "   账户余额：" + balc;
            }
            ui->lwResult->addItem(tmp);
        }
        //ui->verticalLayout_2->setStretch(0,0,0,1,3,0,0,1,0);
        ui->verticalLayout_2->setStretch(3,3);
        ui->verticalLayout_2->setStretch(4,1);
    }
    else
    {
        ui->lwResult->addItem( "门诊序号无效！");
        return;
    }
}

void Form_xxcx::on_pb5206_clicked()
{
    ui->pb_export->setEnabled(false);
    current_query = "";
    //累计结算信息查询
    dlgDelay->setText("正在提取数据。。。");
    dlgDelay->setModal(true);
    dlgDelay->setNeedClose(false);
    dlgDelay->show();
    qApp->processEvents();

    qrm->exec("delete from tmp_down_5206");

    QJsonObject in;   //医保交易入参信息
    QJsonObject inpu; //data 节点
    inpu.insert("psn_no", psn_no);//
    in.insert("data", inpu); //

    QString info;   //返回信息
    QJsonObject jsonRet; //返回 json 数据

    if( ! pub::call_business("5206", in, info, jsonRet, "", true , manager, request))
    {
        QMessageBox::warning(this, "注意", info);
        qDebug()<<"5206 business return error.";
        qDebug()<<info;
        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();
        return ;
    }


    //查询指定交易出参数据结构
    sq = "select node_name,para_code,para_name,type,len,code_flag,is_key,local_tab,local_col "
         " from com_down_para where in_out = 'out' and busi_code = '5206' ";
    qrm->exec(sq);

    QStringList para_code_out,para_type_out;

    while(qrm->next()){
        para_code_out << qrm->value(1).toString();
        para_type_out << qrm->value(3).toString();
    }

    int fieldsCount = para_code_out.size();

    if(fieldsCount == 0)    {
        ui->lwResult->addItem( "字段列表无效！");
        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();
        return;
    }


    QJsonArray retData = jsonRet.value("output").toObject().value("cuminfo").toArray();

    int recCount = retData.size();

    if(recCount == 0){
        QMessageBox::information(this, "注意", "5206 查询无结果。");    //返回正常但无数据
        ui->leStatus->setText("");
        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();
        return;
    }

    int recNow = recCount;

    while(recNow > 0){

        recNow--;

        QString fields, values; //字段列表，返回值列表
        int i = 0;
        bool isFirstField = true; //是否是第一个字段。第一个字段的字串不需要前导分隔符
        while(true)
        {
            QString retV;
            if(para_type_out[i] == "decimal")
            {
                retV = QString::number(retData[recNow].toObject().value(para_code_out[i]).toDouble());
            }
            else
            {
                //过滤字段中对 mysql 有干扰的特殊字符，反斜杠，单引号等。
                retV = retData[recNow].toObject().value(para_code_out[i]).toString();
                retV.replace("\\","/");
                retV.replace("'","\\'");
            }

            if(!retV.isEmpty() )  //只保存非空字段
            {
                if(isFirstField)
                {
                    isFirstField = false;
                    fields += para_code_out[i];
                    values += "'" + retV + "'";
                }else{
                    fields += ", " + para_code_out[i];
                    values += ", '" + retV + "'";
                }
            }

            i++;
            if(i >= fieldsCount)    //本行数据是否处理完成
            {
                break;
            }
        }

        //replace 插入数据，重复数据直接替换。对 atinc 字段有影响。
        sq = "insert into tmp_down_5206 (" + fields + ") values (" + values + ")";

        if(!qrm->exec(sq)){
            ui->lwResult->addItem( " 插入记录错误！\nerrMsg:  "+ qrm->lastError().text() + "\n" + sq  + "\n");
            dlgDelay->setNeedClose(true);
            dlgDelay->closeWindow();
            return;

        }
    }

    QStringList desc;
    desc<<"累计查询结果描述："
       <<"总计 = 医保发生的全部费用（包括机构费用和药店费用） = 自付 + 统筹"
      <<"符合范围（包括机构费用和药店费用） = 甲类 + 乙类 - 先行自付"
     <<"合规费用 = 机构符合范围费用 - 起付线，    统筹 = 医保基金报销";
    ui->lwResult->clear();
    ui->lwResult->addItems(desc);

    display5206();
    dlgDelay->setNeedClose(true);
    dlgDelay->closeWindow();

}

void Form_xxcx::display5206()
{
    QString sum, group, year, year_month, ord;
    sum = "";
    year = "";
    year_month = "";
    group = "";
    ord = "";

    if(ui->cb_group->isChecked())
    {
        sq = "SELECT dic0.dic_label 险种, YEAR 年度, dic1.dic_label 累计类别, cum 金额 ";
        sum = " sum(cum) ";
        group = " GROUP BY insutype, YEAR, cum_type_code ";
        ord = " order by year, dic0.dic_label, dic1.dic_label";
    }
    else
    {
        sq = "SELECT dic0.dic_label 险种, YEAR 年度, cum_ym 月份,"
             " dic1.dic_label 累计类别, cum 金额 ";
        ord = " order by cum_ym, dic0.dic_label, dic1.dic_label";
    }

    if(ui->cb_thisyear->isChecked())
    {
        year = " where year = year(curdate()) ";
    }

    //sq = "SELECT dic0.dic_label 险种, YEAR 年度, dic1.dic_label 累计类别, cum 金额 "
    sq += " FROM ( SELECT insutype, YEAR,cum_ym, cum_type_code, " ;
    sq += sum + " cum FROM tmp_down_5206 " + year + group;
    sq += ") base"
          " LEFT JOIN com_dict_new dic1 ON base.cum_type_code = dic1.dic_value"
          " AND dic1.dic_type = 'CUM_TYPE_CODE'"
          " LEFT JOIN com_dict_new dic0 ON base.insutype = dic0.dic_value"
          " AND dic0.dic_type = 'INSUTYPE'" + ord;


    //sq +=

    qDebug()<<"医保支付累计："<<sq;


    mdDownResult->setQuery(sq, pub::db_m);

    if(mdDownResult->rowCount() < 1)
    {
        ui->lwResult->addItem( " 查询无结果！ ");
        return;
    }

    ui->tvResult->setModel(mdDownResult);
    if(ui->cb_group->isChecked())
    {
        pub::setColumnWidth(ui->tvResult, "0.2^0.1^0.2^0.1^0^0^0^0^0", ui->tvResult->width());
    }
    else
    {
        pub::setColumnWidth(ui->tvResult, "0.2^0.1^0.1^0.25^0.1^0^0^0^0", ui->tvResult->width());
    }
    //ui->verticalLayout_2->setStretch(3,1);
    ui->verticalLayout_2->setStretch(4,3);

    last_query = "m" + sq;
    ui->pb_export->setEnabled(true);

}

void Form_xxcx::on_cb_thisyear_clicked()
{
    display5206();
}

void Form_xxcx::on_cb_group_clicked()
{
    display5206();
}

void Form_xxcx::on_deStart_dateChanged(const QDate &date)
{
    ui->deEnd->setDate(date);
}

void Form_xxcx::on_pb9560_clicked()
{
    ui->pb_export->setEnabled(false);
    current_query = "history";
    QJsonObject in, inpu;

    inpu.insert("psn_name", ui->leXm->text());//人员姓名	字符型	50		Y
    inpu.insert("certno", idenno);//身份证号码	字符型	50		Y
    //inpu.insert("chfpdr_code", ybysdm);//医师编号	字符型	30		Y
    inpu.insert("mdtrt_id", ui->leJzid->text());//就诊id	字符型	30		Y

    in.insert("data",inpu);

    dlgDelay->setText("从医保获取数据。。。");
    dlgDelay->setModal(true);
    dlgDelay->setNeedClose(false);
    dlgDelay->show();
qApp->processEvents();
    call_5960(in);

    dlgDelay->setNeedClose(true);
    dlgDelay->closeWindow();
}

void Form_xxcx::call_5960(QJsonObject &inpu)
{
    // root -- > input -- > data
    // inpu -> inpud.data, inpud-> in.input

    QJsonObject jsonRet;    //医保交易返回的Json数据
    QString info;   //如果返回错误，保存错误信息

    if( ! pub::call_business("5960", inpu, info, jsonRet, "", true , manager, request))
    {
        QMessageBox::warning(this, "注意", info);
        return ;
    }

    //qDebug()<<"jsonRet"<<jsonRet;

    QJsonArray ret = jsonRet.value("output").toObject().value("feelistinfo").toArray();


    if(ret.size() == 0)
    {
        QMessageBox::warning(this, "注意", "查询不到3个月内的医保记录。");
        return ;
    }
    qro->exec("delete from med_history");
    for(int i = 0; i< ret.size(); i++){
        sq = "insert into med_history (fee_ocur_time, hilist_name, spec, cnt, setl_flag,memo) values(";
        sq += "to_date('"+ret[i].toObject().value("fee_ocur_time").toString()+"','yyyy-mm-dd hh24:mi:ss'),";
        sq += "'"+ret[i].toObject().value("hilist_name").toString()+"',";
        sq += "'"+ret[i].toObject().value("spec").toString()+"',";
        sq += QString::asprintf("%.2f", ret[i].toObject().value("cnt").toDouble())+",";
        sq += "'"+ret[i].toObject().value("setl_falg").toString()+"',";
        QString memo;
        if(!ret[i].toObject().value("sin_dos_dscr").toString().isEmpty()){
            memo += "单次剂量：" + ret[i].toObject().value("sin_dos_dscr").toString() + "\n";
        }
        if(!ret[i].toObject().value("used_frqu_dscr").toString().isEmpty()){
            memo += "使用频次：" + ret[i].toObject().value("used_frqu_dscr").toString() + "\n";
        }
        if(!ret[i].toObject().value("drug_unit").toString().isEmpty()){
            memo += "最小包数量：" + ret[i].toObject().value("drug_unit").toString() + "\n";
        }
        if(!ret[i].toObject().value("fixmedins_type").toString().isEmpty()){
            memo += "机构标识：" + ret[i].toObject().value("fixmedins_type").toString() + "\n";
        }
        if(!ret[i].toObject().value("drug_used_prd_days").toString().isEmpty()){
            memo += "可用天数：" + ret[i].toObject().value("drug_used_prd_days").toString() + "\n";
        }
        if(!ret[i].toObject().value("drug_used_rem_days").toString().isEmpty()){
            memo += "剩余天数：" + ret[i].toObject().value("drug_used_rem_days").toString() + "\n";
        }
        if(!ret[i].toObject().value("next_drug_date").toString().isEmpty()){
            memo += "下次开药日期：" + ret[i].toObject().value("next_drug_date").toString() ;
        }

        sq += "'" + memo + "')";
        qro->exec(sq);

        qDebug()<<sq;
    }
    sq = "select to_char(fee_ocur_time,'yyyy-mm-dd') 时间 ,hilist_name 项目名称, spec 规格, "
         "cnt 数量, setl_flag 结算标志 , memo"
         " from med_history order by fee_ocur_time ";

    mdDownResult->setQuery(sq, pub::db_o);

    ui->tvResult->setModel(mdDownResult);
    pub::setColumnWidth(ui->tvResult, "0.2^0.3^0.2^0.1^0.1", ui->tvResult->width());

    last_query = "o" + sq;
    ui->pb_export->setEnabled(true);

}

void Form_xxcx::on_tvResult_clicked(const QModelIndex &index)
{
    QString t = "" ;
    ui->lwResult->clear();
    if(current_query == "history")  //远程查询
    {

        ui->lwResult->addItem(index.siblingAtColumn(5).data().toString()) ;
    }
    else
    {
        ui->lwResult->addItem( "无关联信息");
    }

}

void Form_xxcx::on_pb_export_clicked()
{

    ui->pb_export->setEnabled(false);

    QString db = last_query.left(1);
    last_query.replace(0, 1, "");

    if(db == "o")
    {
        pub::export_sql_to_excel(last_query, qro);
    }
    else
    {
        pub::export_sql_to_excel(last_query, qrm);
    }

}

